package com.example.permission.common.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;

/**
 * easypoi excel导入导出
 *
 * @author mozhu
 * @date 2021/9/22 10:22
 */
public class ExcelEasyExcelUtil {

    private static final Logger logger = LogManager.getLogger(ExcelEasyExcelUtil.class);
    private static final String[] XLS_XLSX_CSV = {"xls", "xlsx", "csv"};

    /**
     * 导出excel(百万性能较差)
     *
     * @param response 响应
     * @param fileName 文件名称
     * @param tClass   实体类 @ExcelProperty注解对应别名
     * @param dataList 数据列表
     * @author mozhu
     * @date 2021-09-22 10:58:55
     */
    public static void exportExcel(HttpServletResponse response, String fileName, Class<?> tClass, List<?> dataList) {
        if (CollectionUtils.isEmpty(dataList)) {
            return;
        }
        try {
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8") + ".xlsx");
            WriteCellStyle headWriteCellStyle = new WriteCellStyle();
            WriteFont headWriteFont = new WriteFont();
            headWriteFont.setFontHeightInPoints((short) 12);
            headWriteFont.setBold(false);
            headWriteCellStyle.setWriteFont(headWriteFont);
            headWriteCellStyle.setShrinkToFit(true);
            HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, new WriteCellStyle());
            EasyExcel.write(response.getOutputStream(), tClass).registerWriteHandler(horizontalCellStyleStrategy).sheet(fileName).doWrite(dataList);
        } catch (IOException e) {
            logger.error("导出失败，失败原因：{}", e);
        }

    }


    /**
     * 读取excel
     *
     * @param multipartFile 文件
     * @param tClass        返回实体类 @ExcelProperty注解对应别名
     * @return {@link List<T> }
     * @author mozhu
     * @date 2021-09-22 10:30:42
     */
    public static <T> List<T> readExcel(MultipartFile multipartFile, Class<T> tClass) {
        if (multipartFile == null) {
            return null;
        }
        try {
            String fileName = multipartFile.getOriginalFilename().toLowerCase();
            // 获取Excel后缀名
            String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
            if (!Arrays.asList(XLS_XLSX_CSV).contains(fileType)) {
                return null;
            }
            return EasyExcel.read(multipartFile.getInputStream()).head(tClass).sheet().doReadSync();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
